package com.jdragon.common.utils;

import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author: Jdragon
 * @email: 1061917196@qq.com
 * @Date: 2020.03.18 20:22
 * @Description: BeanUtils的封装工具类
 */
public class Bean2Utils {
    @SneakyThrows
    public static <T> T copyProperties(Object source,Class<T> Class,String...ignore) {
        T object = Class.newInstance();
        BeanUtils.copyProperties(source,object,ignore);
        return object;
    }
    @SneakyThrows
    public static <T> T copyPropertiesNotNull(Object source,Class<T> Class) {
        T object = Class.newInstance();
        BeanUtils.copyProperties(source,object,getNullPropertyNames(source));
        return object;
    }

    @SneakyThrows
    public static <T> T copyPropertiesNotNull(Object source,T target) {
        BeanUtils.copyProperties(source,target,getNullPropertyNames(source));
        return target;
    }

    public static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}
